package com.anche.demo.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: TokenFilter
 * @Description: TODO
 * @date: 2023/1/11 14:31
 * @Auther: hey
 */
@Component
@Slf4j
public class TokenFilter implements Filter {

    private static final String localUrl="localhost:8080";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("filterConfig:{}",filterConfig.getInitParameterNames());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        log.info("TokenFilter doFilter 我拦截到了请求");
        String domain = httpRequest.getParameter("domain");
        Map<String, String[]> parameterMap = httpRequest.getParameterMap();
        if(Objects.nonNull(domain)){
            String path = httpRequest.getRequestURL().toString();
            path.replace(localUrl,domain);
            //bb通过http调用b 然后设置response
//            request.getRequestDispatcher(path).forward(request,response);
            HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {
                /**
                 * 当调用request.getHeader("token")时，则获取请求参数中token值并当做Header的值返回
                 *
                 * @param name
                 * @return
                 */
                @Override
                public String getHeader(String name) {
                    // 先从原本的Request中获取头，如果为空且名字为token，则从参数中查找并返回
                    String superHeader = super.getHeader(name);
                    if ("domain".equals(name) && StringUtils.isEmpty(superHeader)) {
                        String token = ((HttpServletRequest) request).getServletPath();
                        if (StringUtils.isNotEmpty(token)) {
                            return superHeader+token;
                        }
                    }
                    return superHeader;
                }
            };
            chain.doFilter(requestWrapper,response);
        }else {

            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
